package cn.sylinx.horm.example.section16;

import java.io.Serializable;

import cn.sylinx.horm.core.SqlClient;
import cn.sylinx.horm.starter.CommonStarter;
import cn.sylinx.horm.transaction.jdbc.TransactionSupport;
import cn.sylinx.horm.util.Ret;

public class Section16 {

    static final String CONFIG_FILE = "section16.properties";

    public static void main(String[] args) {

        CommonStarter commonStarter = new CommonStarter(CONFIG_FILE);
        commonStarter.start(); // 启动

        //testTransactionOk();
        testTransactionError();
    }

    static void testTransactionOk() {

        SqlClient sqlClient = SqlClient.getDefaultClient();

        TransactionSupport transactionSupport = sqlClient.getTransactionSupport();

        Ret ret = transactionSupport.transaction(() -> {

            MyExample16 myExample16 = new MyExample16();
            myExample16.setFieldNumber("number");
            myExample16.setFieldName("name");
            Serializable pk = sqlClient.save(myExample16);
            System.out.println("save in trans, pk -> " + pk);

            MyExample16 myExample16_1 = new MyExample16();
            myExample16_1.setFieldNumber("number1");
            myExample16_1.setFieldName("name1");
            Serializable pk1 = sqlClient.save(myExample16_1);
            System.out.println("save in trans, pk1 -> " + pk1);

            return Ret.success();
        });

        System.out.println("事务是否成功 " + ret.isSuccess());
    }
    
    static void testTransactionError() {

        SqlClient sqlClient = SqlClient.getDefaultClient();

        TransactionSupport transactionSupport = sqlClient.getTransactionSupport();

        Ret ret = transactionSupport.transaction(() -> {

            MyExample16 myExample16 = new MyExample16();
            myExample16.setFieldNumber("number111");
            myExample16.setFieldName("name111");
            Serializable pk = sqlClient.save(myExample16);
            System.out.println("save in trans, pk -> " + pk);

            int a = 0;
            
            System.out.println(10 / a);
            
            return Ret.success();
        });

        System.out.println("事务是否成功 " + ret.isSuccess());
        System.out.println("事务失败原因： " + ret.getCause().getMessage());
    }
}
